package xyz.scootaloo.kami.server.model.dao

import org.ktorm.dsl.*
import org.ktorm.entity.*
import xyz.scootaloo.kami.server.model.SysTask
import xyz.scootaloo.kami.server.model.SysTasks
import xyz.scootaloo.kami.server.model.tasks
import xyz.scootaloo.kami.server.standard.currentTimeMillis
import xyz.scootaloo.kami.server.verticle.database

/**
 * @author flutterdash@qq.com
 * @since 2022/2/23 14:59
 */
object TaskDAO {

    fun listIfRunning(): List<SysTask> {
        return database.from(SysTasks)
            .select()
            .where { (SysTasks.state) eq SysTask.RUNNING }
            .map(SysTasks::createEntity)
    }

    fun batchUpdatePayload(records: List<Pair<Int, String>>) {
        database.batchUpdate(SysTasks) {
            for ((recordId, payload) in records) {
                item {
                    set(it.payload, payload)
                    where {
                        it.id eq recordId
                    }
                }
            }
        }
    }

    fun updateTaskState(recordId: Int, state: Int) {
        val dbTask = database.tasks.find { it.id eq recordId } ?: return
        dbTask.state = state
        dbTask.flushChanges()
    }

    fun store(dbTask: SysTask) {
        dbTask.created = currentTimeMillis()
        database.useTransaction {
            database.tasks.add(dbTask)
        }
    }

}